import re

from django.contrib.auth import login
from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.urls import reverse
from django_redis import get_redis_connection

from apps.oauth.models import OAuthQQUser
from apps.oauth.utils import generic_openid_tocken, get_openid_token
from apps.users.models import User
from utils.response_code import RETCODE
from QQLoginTool.QQtool import OAuthQQ
from mei import settings
from django.http import HttpResponseBadRequest
from itsdangerous import TimedJSONWebSignatureSerializer as Ser
import logging
logger = logging.getLogger('django')
# Create your views here.
from django.views import View
class OauthQQURLView(View):
    def get(self,request):
        state = request.GET.get('next')
        oauth = OAuthQQ(
            client_id=settings.QQ_CLIENT_ID,
            client_secret=settings.QQ_CLIENT_SECRET,
            redirect_uri=settings.QQ_REDIRECT_URI,
            state=state
        )

        login_url = oauth.get_qq_url()
        return JsonResponse({'code':RETCODE.OK, 'errmsg':'ok', 'login_url':login_url})


class OauthUserView(View):
    def get(self,request):
        code = request.GET.get('code')
        if code is None:
            return HttpResponseBadRequest('code错误')

        #创建实例
        qq = OAuthQQ(
            client_id=settings.QQ_CLIENT_ID,
            client_secret=settings.QQ_CLIENT_SECRET,
            redirect_uri=settings.QQ_REDIRECT_URI
        )
        token = qq.get_access_token(code)
        openid = qq.get_open_id(token)

        try:
            qquser = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            # return render(request, 'oauth_callback.html',context={'openid':openid})

            openid_tocken = generic_openid_tocken(openid)
            return render(request, 'oauth_callback.html', context={'openid':openid_tocken})
        else:
            login(request,qquser.user)
            next = request.GET.get('next')
            if next:
                response = redirect(next)
            else:
                response = redirect(reverse('contents:index'))
            response.set_cookie('username',qquser.user, max_age=15*24*3600)
            return response



        # return render(request, 'oauth_callback.html')

    def post(self, request):
        data = request.POST
        mobile = data.get('mobile')
        password = data.get('password')
        openid = data.get('openid')
        sms_code = data.get('sms_code')
        if not all([mobile, password, sms_code, openid]):
            return HttpResponseBadRequest('参数不全')
        if not re.match(r'^1[3456789]\d{9}$', mobile):
            return HttpResponseBadRequest('手机号不符合规则')
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return HttpResponseBadRequest('密码不符合规则')

        try:
            redis_conn = get_redis_connection('code')
            sms_code_server = redis_conn.get('sms_%s'%mobile)
            if sms_code_server is None:
                return HttpResponseBadRequest('短信验证码失效')
            if sms_code != sms_code_server.decode():
                return HttpResponseBadRequest('短信验证码输入错误')
        except Exception as e:
            return HttpResponseBadRequest('链接数据库不成功')
        openid = get_openid_token(openid)
        if openid is None:
            return HttpResponseBadRequest('openid为空')
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            user = User.objects.create_user(
                username=mobile,
                mobile=mobile,
                password=password
            )

        else:
            if not user.check_password(password):
                return HttpResponseBadRequest('密码不正确')

        try:
            OAuthQQUser.objects.create(
                user=user,
                openid=openid
            )

        except Exception as e:
            logger.error(e)
            return HttpResponseBadRequest('数据库出错')

        login(request,user)
        response = redirect(reverse('contents:index'))
        response.set_cookie('username', user.username, max_age=24*3600*15)
        return response




